import { observable, action, runInAction } from 'mobx'
import { message } from 'antd'
import $http from '../../utils/http'

const fmtGetParams = (params: any) => {
	let data = '?'
	for (let k in params) {
		data += k + '=' + params[k] + '&'
	}
	return data.substring(0, data.length - 1)
}

const defaultParams: any = {
	query: '{}',
	varibles: '{}',
	operationName: ''
}

export class DemoStore {
	@observable count = 88
	@observable apiUrl = ''	//https://test.ivorycapitalasia.cn/upload/sign
	@observable apiType = '/api'
	@observable apiMethod = 'GET'
	@observable apiParams = ''	//{"type":"id"}
	@observable apiResult = ''

	@action inputApi = (value: string) => {
		this.apiUrl = value
	}

	@action methodChange = (type: string) => {
		this.apiMethod = type
	}

	@action typeChange = (type: string) => {
		this.apiType = type

		if (this.apiType === '/graphql') {
			this.apiParams = JSON.stringify(defaultParams, null, '    ')
		} else {
			this.apiParams = ''
		}
	}

	@action inputParams = (value: string) => {
		this.apiParams = value
	}

	@action testApi = () => {
		let jsonData = {}
		let error = null
		try {
			if (this.apiParams) {
				jsonData = JSON.parse(this.apiParams)
			}
		} catch (e) {
			error = e
		}
		if (error) {
			message.error('参数请使用json格式')
			return
		}
		$http.get(this.apiUrl + fmtGetParams(jsonData))
			.then(res => {
				runInAction(() => this.apiResult = JSON.stringify(res, null, '    '))
			})
	}
}

export default new DemoStore()